import React, {useState,useEffect, useCallback, memo} from 'react'
const TodoItem = memo(({item, handleDelete, handleToggle})=>{
    console.log(item.title)
    return <li>
        <input type="checkbox" checked={item.completed} onChange={()=>handleToggle(item)}/>
        <span>{item.title}</span>
        <button onClick={()=>handleDelete(item)}>删除</button>
    </li>
})
// 在组件内只要有状态的更新，都会重新渲染
const Todolist = () => {
    const localList = localStorage.getItem('todo2');
    const [value, setValue] = useState('');
    const [list, setList] = useState(localList?JSON.parse(localList):[]);
    const handleChange = (e) => {
        setValue(e.target.value)
    }
    const add = () => {
        setList([...list, {title: value,completed: false, id: Date.now()}]);
    }
    const handleDelete = useCallback((item) => {
        setList(list=>list.filter(i=>i.id!==item.id))
    },[])
    const handleToggle = useCallback((item) => {
        setList(list=>list.map(i=>{
            if(i.id==item.id){
                return {...i,completed: !item.completed}
            }else{
                return i
            }
        }))
    },[])
    useEffect(()=>{
        localStorage.setItem('todo2', JSON.stringify(list))
    },[list])
    return (
        <div>
            <h1>Todolist-共有{list.length}条</h1>

            <header>
                <input 
                    value={value}
                    onChange={handleChange}
                />
                <button onClick={add}>添加</button>
            </header>
            <ul>
                {
                    list.map(item=>{
                        return <TodoItem key={item.id} item={item} handleDelete={handleDelete} handleToggle={handleToggle}/>
                    })
                }
            </ul>
        </div>
    )
}

export default Todolist